package com.neusoft.neu24.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.neu24.Result.CommonResult;
import com.neusoft.neu24.dto.Aqi2PublicDTO;
import com.neusoft.neu24.entity.Aqi;
import com.neusoft.neu24.mapper.AqiMapper;
import com.neusoft.neu24.service.IAqiService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.neusoft.neu24.constants.RedisConstants.CACHE;

@Service
public class AqiServiceImpl implements IAqiService {

    @Resource
    private AqiMapper aqiMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public CommonResult<List<Aqi2PublicDTO>> listAll2Public() {

        String pcr = stringRedisTemplate.opsForValue().get(CACHE+"aqi");
        if (pcr != null) {
            try {
                return CommonResult.success(new ObjectMapper().readValue(pcr, new TypeReference<List<Aqi2PublicDTO>>() {}));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        List<Aqi2PublicDTO> dtos = BeanUtil.copyToList(aqiMapper.listAll(), Aqi2PublicDTO.class);

        try {
            stringRedisTemplate.opsForValue().set(CACHE+"aqi", new ObjectMapper().writeValueAsString(dtos));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return CommonResult.success(dtos);
    }
}
